<template>
  <van-icon
    :name="value ? 'star' : 'star-o'"
    @click="onCollect"
    :loading="loading"
    :color="value ? '#ffa500' : ''"
  />
</template>

<script>
import { collectArticleAPI, cancleCollectArticleAPI } from '@/api'
export default {
  name: 'collectArticle',
  data () {
    return {
      loading: false
    }
  },
  props: {
    value: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  methods: {
    async onCollect () {
      this.loading = true
      try {
        if (this.value) {
          // 已收藏，取消收藏
          await cancleCollectArticleAPI(this.userId)
        } else {
          // 未收藏，添加收藏
          await collectArticleAPI(this.userId)
        }
        // 更新视图
        this.$emit('input', !this.value)
        this.$toast.success(!this.value ? '收藏成功' : '取消收藏')
      } catch (error) {
        this.$toast.fail('操作失败，请重试！')
      }
      this.loadind = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
